package com.hhl.nativeflutter.flutter;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


import com.hhl.nativeflutter.flutter.view.WebViewFlutterPlugin;

import io.flutter.Log;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.MethodChannel;



/**
 * @author Administrator
 */
public class FlutterMainActivity extends FlutterActivity {

    private static final String ROUTE_PAGE = "route";
    private static final String CHANNEL = "com.hhl.native.io/battery";
    private CountDownTimer timer;
    private MethodChannel methodChannel;

    public static void startFlutterPage(Context context, String routerUrl, String param) {
        context.startActivity(new Intent(context, FlutterMainActivity.class)
                .putExtra(ROUTE_PAGE, (null == routerUrl || routerUrl.isEmpty()) ?
                        '/' + param : routerUrl + param));
    }

    public static void startFlutterPage(Context context, String routerUrl) {
        context.startActivity(new Intent(context, FlutterMainActivity.class)
                .putExtra(ROUTE_PAGE, (null == routerUrl || routerUrl.isEmpty()) ?
                        '/' : routerUrl));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        methodChannel = new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(), CHANNEL);
        WebViewFlutterPlugin.registerWith(getFlutterEngine().getPlugins());
        initFlutterMethod();
        initTimer();
    }


    private void initFlutterMethod() {
        //flutter 调用原生方法
        methodChannel.setMethodCallHandler((call, result) -> {
            switch (call.method) {
                case "getBatteryLevel":
                    //获取电量
                    int battery = getBatteryLevel();
                    if (-1 != battery) {
                        result.success(battery);
                    } else {
                        result.error("ERROR", "get battery level failed", null);
                    }
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + call.method);
            }
        });
    }

    private int getBatteryLevel() {
        int batteryLevel = -1;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
            batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent = new ContextWrapper(getApplicationContext()).
                    registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
                    intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        }
        return batteryLevel;
    }


    private void initTimer() {
        timer = new CountDownTimer(Integer.MAX_VALUE,3000) {
            @Override
            public void onTick(long millisUntilFinished) {
                //原生调用flutter方法
                methodChannel.invokeMethod("UpdateBattery", getBatteryLevel(), new MethodChannel.Result() {
                    @Override
                    public void success(@Nullable Object result) {
                        Log.e("methodChannel","success");
                    }

                    @Override
                    public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
                        Log.e("methodChannel","error"+errorMessage);
                    }

                    @Override
                    public void notImplemented() {
                        Log.e("methodChannel","notImplemented");
                    }
                });
            }

            @Override
            public void onFinish() {
            }
        };
        timer.start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != timer) {
            timer.cancel();
        }
    }
}
